#include "gameboard.h"
#include <QGraphicsScene>
#include <QGraphicsRectItem>
#include <QGraphicsEllipseItem>
#include <QGraphicsSimpleTextItem>

GameBoard::GameBoard(QWidget *parent)
    : QGraphicsView(parent), m_scene(new QGraphicsScene(this))
{
    setScene(m_scene);
    setRenderHint(QPainter::Antialiasing);
    setMinimumSize(600, 600);

    // 初始化玩家棋子
    QColor colors[] = {Qt::red, Qt::blue, Qt::green};
    for(int i=0; i<3; ++i){
        m_players[i] = new QGraphicsEllipseItem(0, 0, 40, 40);
        m_players[i]->setBrush(colors[i]);
        m_players[i]->setZValue(1); // 确保显示在最上层
        m_scene->addItem(m_players[i]);
    }

    createGrid();
    reset();
}

void GameBoard::createGrid() {
    // 创建9x9网格和编号
    for(int y=0; y<BOARD_SIZE; ++y){
        for(int x=0; x<BOARD_SIZE; ++x){
            // 绘制格子
            auto cell = new QGraphicsRectItem(
                x*GRID_SIZE, y*GRID_SIZE, GRID_SIZE, GRID_SIZE);
            cell->setBrush(Qt::lightGray);
            m_scene->addItem(cell);

            // 计算蛇形编号
            int pos = y*BOARD_SIZE + ((y%2 == 0) ? x : (BOARD_SIZE-1 -x));

            // 添加位置编号
            auto text = new QGraphicsSimpleTextItem(QString::number(pos));
            text->setPos(x*GRID_SIZE +5, y*GRID_SIZE +5);
            m_scene->addItem(text);
        }
    }
}

QPointF GameBoard::calculatePosition(int pos) const {
    int row = pos / BOARD_SIZE;
    int col = (row%2 == 0) ?
                  pos % BOARD_SIZE :
                  (BOARD_SIZE-1) - (pos % BOARD_SIZE);

    // 添加位置偏移防止重叠
    QPointF base(col * GRID_SIZE + 10, row * GRID_SIZE + 10);
    switch(pos % 3) {
    case 0: return base + QPointF(0, 0);   // 1P
    case 1: return base + QPointF(20, 0);  // 2P
    case 2: return base + QPointF(10, 20); // 3P
    }
    return base;
}

void GameBoard::movePlayer(int playerId, int position) {
    if(playerId >=0 && playerId <3) {
        m_players[playerId]->setPos(calculatePosition(position));
    }
}

void GameBoard::reset() {
    // 所有玩家回到起点
    movePlayer(0, 0);
    movePlayer(1, 0);
    movePlayer(2, 0);
}

void GameBoard::setPlayerVisible(int playerId, bool visible) {
    if(playerId >=0 && playerId <3) {
        m_players[playerId]->setVisible(visible);
    }
}
